<template>
  <div class='ele-body ele-body-card'>
    <!-- 顶部卡片 -->
    <a-card
      :bordered='true'
      :body-style="{padding: '20px'}">
      <a-form
        ref='form'
        :label-col='{ md: { span: 7 }, sm: { span: 24 } }'
        :wrapper-col='{ md: { span: 17 }, sm: { span: 24 } }'
        @submit='checkAndPushSubmitConfig'
      >
        <a-divider orientation="left">围栏配置</a-divider>
        <a-row :gutter='8'>
          <a-col :md='14' :sm='24' :xs='24'>
            <a-form-item label='GEO ID:' name='geoId'>
              <a-select v-model:value="form.geoId"  @change="handleChange">
                <a-select-option :value="0">0</a-select-option>
                <a-select-option :value="1">1</a-select-option>
                <a-select-option :value="2">2</a-select-option>
                <a-select-option :value="3">3</a-select-option>
                <a-select-option :value="4">4</a-select-option>
                <a-select-option :value="5">5</a-select-option>
                <a-select-option :value="6">6</a-select-option>
                <a-select-option :value="7">7</a-select-option>
                <a-select-option :value="8">8</a-select-option>
                <a-select-option :value="9">9</a-select-option>
                <a-select-option :value="10">10</a-select-option>
                <a-select-option :value="11">11</a-select-option>
                <a-select-option :value="12">12</a-select-option>
                <a-select-option :value="13">13</a-select-option>
                <a-select-option :value="14">14</a-select-option>
                <a-select-option :value="15">15</a-select-option>
                <a-select-option :value="16">16</a-select-option>
                <a-select-option :value="17">17</a-select-option>
                <a-select-option :value="18">18</a-select-option>
                <a-select-option :value="19">19</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md='10' :sm='24' :xs='24'>
          </a-col>
        </a-row>

        <a-row :gutter='8'>
          <a-col :md='14' :sm='24' :xs='24'>
            <a-form-item label="Model:" name="geoMode">
              <a-select v-model:value="form.geoMode">
                <a-select-option :value="0">Disable</a-select-option>
                <a-select-option :value="1">Entering the zone</a-select-option>
                <a-select-option :value="2">Exiting the zone</a-select-option>
                <a-select-option :value="3">Both entering and exiting</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md='10' :sm='24' :xs='24'>
          </a-col>
        </a-row>

        <a-row :gutter='8'>
          <a-col :md='14' :sm='24' :xs='24'>
            <a-form-item label='百度坐标系纬度:' name='bdLatitude'>
              <a-input-number
                :step="0.000001"
                string-mode
                :min="0" v-model:value='form.bdLatitude' style="width: 180px" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md='10' :sm='24' :xs='24'>
          </a-col>
        </a-row>

        <a-row :gutter='8'>
          <a-col :md='14' :sm='24' :xs='24'>
            <a-form-item label='百度坐标系经度:' name='bdLongitude'>
              <a-input-number
                :step="0.000001"
                string-mode
                :min="0" v-model:value='form.bdLongitude' style="width: 180px" allow-clear />
              <a-button style="margin-left: 25px;" type='primary' html-type='button' @click='selectMapAction'>地图选择位置</a-button>
            </a-form-item>
          </a-col>
          <a-col :md='10' :sm='24' :xs='24'>
          </a-col>
        </a-row>

        <a-row :gutter='8'>
          <a-col :md='14' :sm='24' :xs='24'>
            <a-form-item label='半径大小(m):' name='radius'>
              <a-input-number :min="50" :max="6000000" v-model:value='form.radius' style="width: 180px" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md='10' :sm='24' :xs='24'>
          </a-col>
        </a-row>

        <a-row :gutter='8'>
          <a-col :md='14' :sm='24' :xs='24'>
            <a-form-item label='检查周期(秒):' name='checkInterval'>
              <a-input-number :min="0" :max="600000" v-model:value='form.checkInterval' style="width: 180px" allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md='10' :sm='24' :xs='24' />
        </a-row>

        <a-row :gutter='8'>
          <a-col :md='14' :sm='24' :xs='24'>
            <a-form-item label='StartTime(HHMM):' name='startTime'>
              <a-input v-model:value='form.startTime' placeholder='请输入检测开始时间' allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md='10' :sm='24' :xs='24'>
          </a-col>
        </a-row>

        <a-row :gutter='8'>
          <a-col :md='14' :sm='24' :xs='24'>
            <a-form-item label='EndTime(HHMM):' name='endTime'>
              <a-input v-model:value='form.endTime' placeholder='请输入检测结束时间' allow-clear />
            </a-form-item>
          </a-col>
          <a-col :md='10' :sm='24' :xs='24'>
          </a-col>
        </a-row>

        <a-row :gutter='8'>
          <a-col :md='14' :sm='24' :xs='24'>
            <a-form-item label="State Model:" name="stateMode">
              <a-select v-model:value="form.stateMode">
                <a-select-option :value="0">Report upon getting the state for the first time</a-select-option>
                <a-select-option :value="1">not report uniting state changes</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md='10' :sm='24' :xs='24'>
          </a-col>
        </a-row>

        <a-row :gutter='8'>
          <a-col :md='2' :sm='24' :xs='24'>
          </a-col>
          <a-col :md='8' :sm='24' :xs='24'>
            <a-button type='primary' html-type='submit' :loading='formSubmitLoading'>
              提交
            </a-button>
            <a-button style="margin-left: 25px;" type='primary' html-type='button' @click='readGEO' :loading='readLoading'>
              读取
            </a-button>
          </a-col>
          <a-col :md='8' :sm='24' :xs='24'>
          </a-col>
          <a-col :md='6' :sm='24' :xs='24'></a-col>
        </a-row>
      </a-form>
    </a-card>

    <device-vehicle-config-circle-geofence-bmap v-if="showSelectPoint" v-model:visible="showSelectPoint" :point="currentPoint" @done="fillPoint" />
  </div>
</template>

<script>

import {DeviceCommandDownQueueApi} from '@/api/property/DeviceCommandDownQueueApi';
import { message } from 'ant-design-vue';
import {VehicleConfigCircleGeofenceApi} from "@/api/property/vechile/VehicleConfigCircleGeofenceApi";
import DeviceVehicleConfigCircleGeofenceBmap from './vehicle-config-circle-geofence-bmap.vue'

export default {
  name: 'DeviceVehicleConfigCircleGeofence',
  components: {
    DeviceVehicleConfigCircleGeofenceBmap
  },
  props: {
    data: Object
  },
  async created() {
    this.getDetail();
  },
  data() {
    return {
      form : {},
      currentConfig : {},
      currentPoint : {},
      loading : false,

      formSubmitLoading : false,
      formSubmitTimer : undefined,

      readLoading : false,
      readTimer : undefined,
      showSelectPoint : false
    };
  },
  methods: {
    fillPoint(point) {
      console.log("子页面回调")
      console.log(point);
      if (point.latitude > 0 && point.longitude > 0) {
        this.form.bdLatitude = point.latitude.toFixed(6);
        this.form.bdLongitude = point.longitude.toFixed(6);
        this.form.latitude = 0;
        this.form.longitude = 0;
        this.form.gcjLatitude = 0;
        this.form.gcjLongitude = 0;
      }
    },
    selectMapAction () {
      this.currentPoint = {
        latitude : this.form.bdLatitude,
        longitude : this.form.bdLongitude
      };
      this.showSelectPoint = true;
    },
    handleChange (value) {
      this.getDetail(value);
    },
    getDetail(geoId) {
      let that = this;
      let params = {
        "recordId" : this.data.recordId,
        "geoId" : geoId || 0
      };
      VehicleConfigCircleGeofenceApi.list(params).then(result => {
        if (result && result.length == 1) {
          that.form = result[0] || {"geoId" : params.geoId};
        } else {
          that.form = {"geoId" : params.geoId};
        }
        that.currentConfig = JSON.parse(JSON.stringify(that.form));
      });
    },

    checkProcess(sceneDictate, clearCallback, callback) {
      let params = {
        recordId: this.data.recordId,
        sceneDictate: sceneDictate
      };
      let result = DeviceCommandDownQueueApi.workingDetail2(params);
      result
        .then(result => {
          if (!result || !result.dcdqId) { //处理完成了
            clearCallback && clearCallback(); //去掉菊花+清除循环调用
            callback && callback(); //用户自定义
          }
        })
        .catch(() => {
          clearCallback && clearCallback(); //去掉菊花+清除循环调用
        });
    },


    //-------提交
    clearSubmitConfig(){
      this.formSubmitLoading = false;
      clearInterval(this.formSubmitTimer);
    },

    checkSubmitConfig(){
      let that = this;
      this.checkProcess(5, this.clearSubmitConfig, function(){
        that.getDetail();
      });
    },

    checkAndPushSubmitConfig() {
      let workerDetailparams = {
        recordId: this.data.recordId,
        sceneDictate: 5
      };
      let that = this;
      let existWorkerResult = DeviceCommandDownQueueApi.workingDetail2(workerDetailparams);
      existWorkerResult
        .then(workResult => {
          console.log(workResult);
          if (!workResult || !workResult.dcdqId) { //处理完成了
            that.pushSubmitConfigSubmit();
          } else {
            message.error('上一个配置还在推送中，请稍后重试');
            return;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    },
    pushSubmitConfigSubmit() {
      if (this.form.geoMode == 0 && (this.form.latitude > 0 || this.form.longitude > 0)) {
        message.error('mode是禁止的，设置无效');
        return;
      }
      this.loading = true;
      let updateDataRecord = {
        recordId: this.data.recordId,
        templateCode: 'vehicle',
        updateData: JSON.stringify({ old: this.currentConfig, update: this.form}),
        dictate : 5, //AT+GTGEO=
        sceneDictate : 5 //GTGEO
      };
      let result = DeviceCommandDownQueueApi.add(updateDataRecord);
      result
        .then(result => {
          this.loading = false;
          message.success(result.message);

          this.formSubmitLoading = true; //转圈
          this.formSubmitTimer = setInterval(this.checkSubmitConfig, 5000);
        })
        .catch(() => {
          this.loading = false;
        });
    },
    //----读取
    clearReadSubmitConfig(){
      this.readLoading = false;
      clearInterval(this.readTimer);
    },

    checkReadSubmitConfig(){
      let that = this;
      this.checkProcess(604, this.clearReadSubmitConfig, function(){
        that.getDetail();
      });
    },

    readGEO() {
      let workerDetailParams = {
        recordId: this.data.recordId,
        sceneDictate: 604
      };
      let that = this;
      let existWorkerResult = DeviceCommandDownQueueApi.workingDetail2(workerDetailParams);
      existWorkerResult
        .then(workResult => {
          console.log(workResult);
          if (!workResult || !workResult.dcdqId) { //处理完成了
            that.pushSubmitReadSubmit();
          } else {
            message.error('上一个配置还在推送中，请稍后重试');
            return;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    },
    pushSubmitReadSubmit() {
      this.loading = true;
      let updateDataRecord = {
        recordId: this.data.recordId,
        templateCode: 'vehicle',
        updateData: JSON.stringify({}),
        dictate : 604, //读取GTSPD
        sceneDictate : 604
      };
      let result = DeviceCommandDownQueueApi.add(updateDataRecord);
      result
        .then(result => {
          this.loading = false;
          message.success(result.message);

          this.readLoading = true; //转圈
          this.readTimer = setInterval(this.checkReadSubmitConfig, 5000);
        })
        .catch(() => {
          this.loading = false;
        });
    },

  }
};
</script>
<style scoped>
/** 用户卡片 */
.workplace-user-card .ele-cell-content {
  overflow: hidden;
}

.workplace-user-card h4 {
  margin-bottom: 6px;
}
</style>
